<template>
  <el-dialog
    v-dialogDrag
    :title="dialogTitle"
    :close-on-click-modal="false"
    :visible.sync="dialogVisible"
    class="dialogStyleMiddle"
    :before-close="cancel"
  >
    <el-form
      ref="form"
      :model="sysRole"
      :rules="rules"
      label-width="80px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="sysRole.roleName" size="medium" placeholder />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="权限字符" prop="roleKey">
            <el-input v-model="sysRole.roleKey" size="medium" placeholder>
              <template slot="prepend">{{ roleKey }}</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色顺序" prop="roleSort">
            <el-input-number
              v-model="sysRole.roleSort"
              size="medium"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色类型" prop="roleKind">
            <el-select v-model="sysRole.roleKind" placeholder="请选择" :disabled="true" size="medium">
              <el-option
                v-for="dict in roleKindOptions"
                :key="dict.dictValue"
                size="medium"
                :disabled="dict.dictValue === '4'?true:false"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="权限范围" prop="dataScope" size="medium">
            <el-select v-model="sysRole.dataScope" size="medium">
              <el-option
                v-for="dict in dataScopeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                size="medium"
                :value="dict.dictValue"
              />
            </el-select>
            <span style="color:red">该角色拥有菜单的默认数据权限</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注信息" prop="remark">
            <el-input v-model="sysRole.remark" :rows="6" type="textarea" size="medium" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">

      <el-button size="medium" @click="cancel">取 消</el-button>
      <el-button size="medium" type="primary" :disabled="btnDisabled" @click="submitForm">保 存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getPostCode } from '@/api/system/post'
import { getRoleByRoleId, getMaxRoleSort, checkRoleNameUnique, checkRoleKeyUnique, updateRole, addRole } from '@/api/system/role'
export default {
  name: 'AddDialog',
  props: {
    dataScopeOptions: {
      type: Array,
      default: () => []
    },
    roleKindOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    // 角色名称查询重复
    const checkRoleName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('名称不能为空'))
      } else {
        const roleId = this.sysRole.roleId
        const roleName = value
        checkRoleNameUnique(roleId, roleName).then(res => {
          if (res.data === '1') {
            return callback(new Error('名称已经存在'))
          } else {
            callback()
          }
        })
      }
    }

    // 权限字符查询重复
    const checkRoleKey = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('权限字符不能为空'))
      } else {
        const roleId = this.sysRole.roleId
        const roleKey = this.roleKey + value
        checkRoleKeyUnique(roleId, roleKey).then(res => {
          if (res.data === '1') {
            return callback(new Error('权限字符已经存在'))
          } else {
            callback()
          }
        })
      }
    }
    return {
      roleKey: '',
      btnDisabled: false,
      // 弹出的对话框的标题
      dialogTitle: '',
      // 对话框是否弹出显示
      dialogVisible: false,
      // 角色表单
      sysRole: {
        roleId: '',
        roleName: '',
        roleKey: '',
        roleSort: '',
        roleKind: '',
        menuIds: [],
        remark: '',
        dataScope: '',
        deptIds: '',
        status: '0'
      },
      rules: {
        roleName: [
          { required: true, validator: checkRoleName, trigger: 'blur' }
        ],
        roleKey: [
          { required: true, validator: checkRoleKey, trigger: 'blur' }
        ],
        roleSort: [
          { required: true, message: '角色顺序不能为空', trigger: 'blur' }
        ],
        dataScope: [
          { required: true, message: '权限范围是必选项', trigger: 'blur' }
        ],
        roleKind: [
          { required: true, message: '角色类型是必选项', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getPostCode()
  },
  methods: {
    handleAdd(title, id, roleKind) {
      this.dialogVisible = true
      this.dialogTitle = title
      if (id) {
        this.selectRoleByRoleId(id)
      } else {
        this.getMaxRoleSort()
        this.sysRole.roleKind = roleKind
      }
    },
    getPostCode() {
      getPostCode().then(res => {
        this.roleKey = res.data
      })
    },
    // 获取岗位顺序的最大值
    getMaxRoleSort() {
      getMaxRoleSort().then(resp => {
        this.sysRole.roleSort = resp.data + 1
      })
    },
    selectRoleByRoleId(id) {
      getRoleByRoleId(id).then(resp => {
        if (resp) {
          const { roleId, roleName, roleSort,
            status, roleKind, dataScope, remark } = resp.data.role
          const roleKey = resp.data.role.roleKey.substr(this.roleKey.length)

          this.sysRole = { ...this.sysRole, roleId, roleName, roleKey, roleSort,
            status, roleKind, dataScope, remark }
        }
      })
    },
    // 弹框取消按钮
    cancel() {
      this.dialogVisible = false
      this.btnDisabled = false
      this.emptySysRole()
    },
    emptySysRole() {
      this.sysRole.roleId = ''
      this.sysRole.status = '0'
      this.sysRole.menuIds = []
      this.sysRole.deptIds = ''
      this.resetForm('form')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.btnDisabled = true
          const sysRole = { ...this.sysRole, roleKey: this.roleKey + this.sysRole.roleKey }
          if (this.sysRole.roleId) {
            updateRole(sysRole).then(res => {
              if (res) {
                this.msgSuccess('修改成功')
                this.$parent.getList()
                this.cancel()
              }
            }).catch(() => {
              this.btnDisabled = false
            })
          } else {
            addRole(sysRole).then(res => {
              if (res) {
                this.msgSuccess('新增成功')
                this.$parent.getList()
                this.cancel()
              }
            }).catch(() => {
              this.btnDisabled = false
            })
          }
        }
      })
    }
  }
}
</script>

